<template>
  <div id="dic_warp">
    <affix :label="$t('configLazyLoad.dicConfig.dicConfigList')">
      <configCompositionTwoWindowStyle :leftWidth="8" :rightWidth="16">
        <template slot="card">
          <search
            ref="search1"
            width="125px"
            :inputTitle="$t('configLazyLoad.dicConfig.inputDicName')"
            :loading="tableLoading"
            @add="addDic"
            @refresh="refresh"
            @search="searchByName"
            @inputChange="inputChangeSkillName"
            @turnPage="turnPage"
            :currentPage="currentPage"
            :isReloadIvr="false"
            :showAdvSearch="false"
            :count="count"
            :pageSize="10"
          >
            <template slot="custom-oprate">
              <span @click.stop="importDic" class="icon-text" v-show="hasImport"
                ><i class="icon iconfont icon-daoru"></i
                >{{ $t('config.customer.import') }}</span
              >
              <span @click.stop="exoprtDic" class="icon-text" v-show="hasExport"
                ><i class="icon iconfont icon-daochu1"></i
                >{{ $t('webchat.exportSessionRecord') }}</span
              >
            </template>
          </search>
          <dicTable
            :tableHeader="tableHeader"
            :tableData="tableData"
            @updata="updata"
            @edit="edit"
            :loading="tableLoading"
            @copyJump="copyJump"
          ></dicTable>
        </template>
        <template slot="detail">
          <div
            v-if="showAddEdit || isShowDicConfigEdit"
            class="showDetialTitle"
          >
            {{ firstTitle }}
          </div>
          <dicAddNew
            ref="dicAddNewRefs"
            v-if="showAddEdit"
            :editOrAddForm="editOrAddForm"
            :isNewDic="isNewDic"
            @refresh="refresh"
            :newModel="dicConfigData"
          ></dicAddNew>
          <!--<dicAdd v-if="showAddEdit" :editOrAddForm="editOrAddForm" :isNewDic="isNewDic" @refresh="refresh"></dicAdd>-->
          <!--<dicConfigEdit v-if="isShowDicConfigEdit" :model="dicConfigData" @refresh="refresh" @cancel="cancel"></dicConfigEdit>-->
          <div class="btn_warp" v-show="isSuccess">
            <el-button type="primary" class="primary_btn fr" @click="saveFun">{{
              $t('public.save')
            }}</el-button>
            <el-button class="primary_btn fr cancel" @click="cancel">{{
              $t('public.cancel')
            }}</el-button>
          </div>
        </template>
      </configCompositionTwoWindowStyle>
    </affix>
    <!--字典导入 end==================================================-->
    <el-dialog
      :close-on-click-modal="false"
      modal-append-to-body
      lock-scroll
      title="字典导入"
      :visible.sync="importDicDialog"
      width="50%"
    >
      <div class="btn-wrap">
        <el-button type="info" class="temp-download primary_btn">
          <a href="/static/template/dic_template.xlsx" download>{{
            $t('km.downloadImport')
          }}</a>
        </el-button>
        <!--饿了么上传组件-->
        <el-upload
          class="temp-upload"
          :action="uploadUrl"
          accept=".xls,.xlsx"
          name="upload"
          :data="uploadHeaders"
          :with-credentials="true"
          :on-success="handleSuccess"
          :on-error="handleError"
          :before-upload="beforeUpload"
          :show-file-list="false"
          :disabled="importing"
        >
          <el-button :disabled="importing" class="primary_btn" type="primary">{{
            importing ? $t('km.importing') : $t('km.importName')
          }}</el-button>
        </el-upload>
      </div>
      <div class="import" v-show="importShow">
        <el-row :gutter="20">
          <el-col :span="4" class="label">{{ $t('km.batchNo') }}</el-col>
          <el-col :span="10"
            ><el-input
              v-model.trim="importObj.batchNo"
              :disabled="true"
            ></el-input
          ></el-col>
          <el-col :span="10"
            ><el-input
              v-model.trim="importObj.batchRemark"
              @click.enter="importExcel"
              :placeholder="$t('km.batchNoMark')"
            ></el-input
          ></el-col>
        </el-row>
        <el-button
          class="primary_btn margin-t"
          @click.stop="importExcel"
          type="primary"
          >{{ $t('config.customer.import') }}</el-button
        >
      </div>
      <div class="instructions" v-html="$t('km.importTips3')" v-once></div>
    </el-dialog>
  </div>
</template>
<script>
import Affix from '@/components/ui-modules/affix/Affix'
import configCompositionTwoWindowStyle from '../../../ui-modules/config/configCompositionTwoWindowStyle'
import search from '../channelConfig/base/search'
import dicTable from './dicTable.vue'
import dicAddNew from './dicAddNew.vue'
import { isHasMenu, getDateNo } from '@/utils/m7Utils'
export default {
  name: 'dicManage',
  data () {
    return {
      agents: [],
      currentPage: 1,    //   当前页
      tableHeader: [
        { prop: 'name', label: this.$t('configLazyLoad.dicConfig.dicName') },
        { prop: 'cascade', label: this.$t('configLazyLoad.dicConfig.cascade') },
        { prop: 'handel', label: this.$t('public.operate'), isApp: 'true' }
      ],                        //   自定义 表头
      tableData: [],            //   表格数据
      tableLoading: false,      //   表格  loading
      isShowDicConfigEdit: false,   //   右侧 配置字典
      showAddEdit: false,           //   右侧 添加或编辑字典
      isLoadingAddOrEdit: false,
      firstTitle: this.$t('configLazyLoad.dicConfig.addDic'),
      serachName: '',
      editOrAddForm: {
        _id: '',
        cascade: 1,
        name: ''
      },   // 修改添加字典数据
      dicConfigData: {},
      sdkData: {},
      versionData: {},
      isNewDic: false,
      count: 0,
      isSuccess: false,
      importDicDialog: false, // 字典导入dialog
      uploadUrl: '/fileUpload',
      uploadHeaders: {
        type: 'undefined',
        module: '',
        sessionId: this.$store.state.session.sessionId
      },
      importObj: {
        batchNo: '',
        batchRemark: '',
        fileName: '',
        trueName: ''
      },
      importing: false,
      importShow: false
    }
  },
  computed: {
    hasImport () {
      return isHasMenu('dic_import', this.$store.state.session.user) || this.$store.state.session.user.isAdmin
    },
    hasExport () {
      return isHasMenu('dic_export', this.$store.state.session.user) || this.$store.state.session.user.isAdmin
    }
  },
  watch: {
    importDicDialog (val) {
      if (!val) {
        this.importObj = {
          batchNo: '',
          batchRemark: '',
          fileName: '',
          trueName: ''
        }
        this.importing = false,
        this.importShow = false
      }
    }
  },
  components: {
    configCompositionTwoWindowStyle,
    search,
    dicTable,
    Affix,
    dicAddNew
  },
  methods: {
    saveFun () {
      this.$refs.dicAddNewRefs.onSubmit()
    },
    addDic () {
      this.firstTitle = this.$t('configLazyLoad.dicConfig.addDic')
      this.isNewDic = true
      this.editOrAddForm.cascade = '1'
      this.editOrAddForm.name = ''
      this.editOrAddForm._id = ''
      this.showAddEdit = true
      this.isShowDicConfigEdit = false
      this.dicConfigData = {}
      this.isSuccess = true
    },
    refresh () {
      this.$refs.search1.resetForm()
      this.serachName = ''
      this.isShowDicConfigEdit = false
      this.showAddEdit = false
      this.currentPage = 1
      this.search()
      this.isSuccess = false
    },
    cancel () { // 取消
      this.isShowDicConfigEdit = false
      this.showAddEdit = false
      this.currentPage = 1
      this.isSuccess = false
    },
    searchByName (val) {
      this.isShowDicConfigEdit = false
      this.showAddEdit = false
      this.serachName = val
      this.currentPage = 1
      this.search(val)
    },
    inputChangeSkillName (val) {
      this.serachName = val
    },
    search (val, data) {
      this.tableLoading = true
      var self = this
      this.$store.dispatch('dicQueryList', { page: this.currentPage, limit: 10, name: this.serachName }).then((res) => {
        if (res.success) {
          let tableData = res.list
          // 如果没有最后更新时间的处理
          this.versionData = res.version
          this.tableData = tableData
          this.count = res.count
          this.tableLoading = false
          if (data) {
            //复制成功跳转配置页
            this.showAddEdit = false
            this.isNewDic = false
            this.isLoadingAddOrEdit = true
            this.isShowDicConfigEdit = false
            let editData = this.tableData.filter(item => item._id === data._id)[0]
            this.editOrAddForm._id = editData._id
            this.editOrAddForm.cascade = editData.cascade.toString()
            this.editOrAddForm.name = editData.name
            this.firstTitle = this.$t('configLazyLoad.dicConfig.dicConfig')
            this.isSuccess = true
            this.dicConfigData = data
            this.isLoadingAddOrEdit = false
            this.isShowDicConfigEdit = true
            this.showAddEdit = true
          }
        }
      })
    },
    turnPage (val, searchContent, data) {
      this.currentPage = val
      this.search(searchContent, data)
    },
    updata (val) {
      let id = val._id
      this.showAddEdit = false
      this.isNewDic = false
      this.isLoadingAddOrEdit = true
      this.isShowDicConfigEdit = false
      this.$store.dispatch('dicfindOneAppDic', { _id: id }).then(res => {
        if (res.success) {
          let editData = this.tableData.filter(item => item._id === id)[0]
          this.editOrAddForm._id = editData._id
          this.editOrAddForm.cascade = editData.cascade.toString()
          this.editOrAddForm.name = editData.name
          this.firstTitle = this.$t('configLazyLoad.dicConfig.dicConfig')
          this.isSuccess = true
          this.dicConfigData = res.data
          this.isLoadingAddOrEdit = false
          this.isShowDicConfigEdit = true
          this.showAddEdit = true
          //            this.editOrAddForm.cascade = res.data.cascade
          //            this.editOrAddForm.name = res.data.name
        }
      })
    },
    copyJump (data, flag) {
      this.$store.dispatch('addCache', { type: 'options', data: data })
      if (flag && data) {
        this.turnPage(Math.ceil((this.count + 1) / 10), '', data)
      } else {
        this.search()
      }
    },
    edit (val) {
      let id = val._id
      this.firstTitle = this.$t('configLazyLoad.dicConfig.editDic')
      let editData = this.tableData.filter(item => item._id === id)[0]
      this.isNewDic = false
      this.editOrAddForm._id = editData._id
      this.editOrAddForm.cascade = editData.cascade.toString()
      this.editOrAddForm.name = editData.name
      this.showAddEdit = true
      this.isShowDicConfigEdit = false
    },
    importDic () {
      this.importDicDialog = true
    },
    exoprtDic () {
      let data = {
        Method: 'exportDic',
        Query: {}
      }
      this.$store.dispatch('exportXls', data).then((res) => {
        if (res.success) {
          this.$message.success(this.$t('webchat.exportSuccess'))
        }
      })
    },
    // 上传前 配置上传参数
    beforeUpload (file) {
      if (!file.name) {
        return
      }
      this.uploadHeaders.key = 'file'
      this.uploadHeaders.name = file.name
      let arr = file.name.split('.')
      let arrType = ['xls', 'xlsx']
      this.importing = true
      if (arrType.indexOf(arr[arr.length - 1]) !== -1) {
        return true
      } else {
        this.$message.error(this.$t('km.fileTypeError'))
        return false
      }
    },
    importExcel () {
      this.$store.dispatch('addDictionaryImportTask', this.importObj).then((resp) => {
        if (resp.success) {
          this.$message.success(this.$t('configLazyLoad.questionnaireConfig.importSuccess'))
          this.importDicDialog = false
          setTimeout(() => { // 延时一下，导入异步
            this.refreshData()
          }, 400)
        }
      })
    },
    //      上传成功
    handleSuccess (response) {
      this.importing = false
      if (response.success) {
        this.importObj.batchNo = getDateNo()
        this.importObj.batchRemark = ''
        this.importObj.fileName = response.filePath ? response.filePath.substring(response.filePath.lastIndexOf('/') + 1) : ''
        this.importObj.trueName = response.fileName || ''
        this.importShow = true
      } else {
        this.$message.error(this.$t('message.default_tips'))
      }
    },
    //      失败
    handleError () {
      this.importing = false
      this.$message.error(this.$t('message.default_tips'))
    }
  },
  beforeMount () {
    this.search()
  }
}
</script>
<style lang="stylus">
#dic_warp
  .wrapper
    .overScroll
      overflow-y auto !important
  .wrapper
    .card-group
      height auto
      border-left 1px solid #e6e6e6
  .el-table
    border-left 0
</style>
<style lang="stylus" scoped>
@import '../../../../assets/common.styl'
.btn-wrap
  padding-bottom 10px
  overflow hidden
  .temp-download
    float left
    a
      color #fff
  .temp-upload
    float left
    display inline-block
    margin-left 20px
  .temp-upload-btn
    font-size 12px
    padding 8px 15px
.internetChannelSkillWrap
  .title
    color $c-prompt
    height 30px
    line-height 30px
    padding 3px 10px
    border-bottom 1px solid $c-border1
#dic_warp
  padding 16px
  height calc(100vh - 125px)
  overflow-y auto
  .overScroll
    overflow-y auto
.showDetialTitle
  padding 8px 20px
  font-weight 600
  font-size 14px
.searchWrap
  position relative
  border-left 1px solid #d9d9d9
  border-top 1px solid #d9d9d9
.cancel
  margin-right 20px
.btn_warp
  height 30px
  margin 20px 0
</style>
